﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HCQ2_BLL.Order;
using HCQ2_IBLL;
using HCQ2_IDAL;
using HCQ2_Model;
using HCQ2_Model.Pay;
using HCQ2_Common;
using HCQ2_DI;
using HCQ2_Model.Data;
using System.Transactions;
using HCQ2_Model.ViewModel;
using System.Data;
using System.Web;
using HCQ2_Model.WeiXinApiModel.Model;
using System.Net;
using System.IO;
using Newtonsoft.Json.Linq;
using HCQ2_Common.Log;
using HCQ2_Model.VR.Model;
using HCQ2_Common.SQL;

namespace HCQ2_BLL
{
    public partial class N_OrderBLL : IN_OrderBLL
    {
        private static object obj = new object();

        private static object obj1 = new object();

        private static object obj2 = new object();

        private static object obj3 = new object();

        /// <summary>
        /// 度度圈，微信扫码支付的二维码存放目录
        /// </summary>
        private static readonly string DDQ_QRCODE_PATH = "/uploadFile/DDQRCode";

        /// <summary>
        /// 同层业务
        /// </summary>
        protected readonly IBLLSession bLLSession = SpringHelper.GetObject<IBLLSessionFactory>("BLLSessionFactory").GetBLLSession();


        private IN_OrderDAL OrderDAL
        {
            get {
                return DBSession.IN_OrderDAL;
            }
        }

        public IT_VRShoppingCartDAL ShoppingCartDAL
        {
            get
            {
                return DBSession.IT_VRShoppingCartDAL;
            }
        }

        /// <summary>
        /// 小程序密钥配置数据库操作
        /// </summary>
        public IT_VRWebChartSetDAL VRWebChartSet 
        {
            get {
                return DBSession.IT_VRWebChartSetDAL;
            }
        }

        public OperationResult<TableModel<List<OrderListModel>>> ListOrderList(GetOrderListParams listParams)
        {
            var data = OrderDAL.ListOrderList(listParams);
            var tableModel = data.Data;
            foreach (var order in tableModel.rows)
            {
                order.FileImgUrl = order.FileImgUrl.Replace("~", HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.IndexOf("/api/")));
            }
            data.Data = tableModel;
            return data;
        }
        
        public OperationResult<GetParentOrderListTableModel> ListParentOrderList(GetParentOrderListParams listParams)
        {
            return OrderDAL.ListParentOrderList(listParams);
        }
        
        public OperationResult<GetOrderDetailedModel> GetOrderDetailed(GetOrderDetailedParams detailedParams)
        {
            return OrderDAL.GetOrderDetailed(detailedParams);
        }
        
        public OperationResult<TableModel> ListOrderList(GetPcOrderListParams listParams)
        {
            return OrderDAL.ListOrderList(listParams);
        }
        
        public OperationResult<PaymentAmountModel> GetPaymentAmount(PaymentAmountParams paymentAmountParams)
        {
            //用户
            T_User user = DBSession.IT_UserDAL.FindSingle(w=>w.user_guid.Equals(paymentAmountParams.userid));

            //组装商品ID
            var fileid = new List<int>();
            paymentAmountParams.CommodityIds.ForEach((CommodityInfo) => { fileid.Add(CommodityInfo.CommodityId.Value); });

            //获取所有购买文件的期限价格
            List<T_VRGoodDisiPrice> goodDisiPrices = ShoppingCartDAL.ListFileAllPrice(fileid);

            var mess = new List<string>();
            //商品总价
            decimal TotalPrice = 0;
            //自营商品总价
            decimal SupplyTypeTotalPrice = 0;
            foreach (var commodify in paymentAmountParams.CommodityIds)
            {
                T_DocumentInfo documentInfo = DBSession.IT_DocumentInfoDAL.FindSingle(w => w.file_id == commodify.CommodityId);

                T_VRGoodDisiPrice commodifyGoodDisi = GetPriceInfo(goodDisiPrices, commodify);

                if (commodifyGoodDisi == null)
                {
                    mess.Add($"未找到商品：{documentInfo.file_name} 购买期限：{commodify.PurchasePeriod}个月的价格信息，请刷新重试");
                }
                else
                {
                    //累加商品总价
                    TotalPrice = TotalPrice + commodifyGoodDisi.ori_price;

                    //自营商品总价
                    if (documentInfo.supplyType == 1)
                    {
                        SupplyTypeTotalPrice = SupplyTypeTotalPrice + commodifyGoodDisi.ori_price;
                    }
                }
            }

            //如果有价格不存的信息，返回错误
            if (mess.Count > 0)
            {
                return new OperationResult<PaymentAmountModel>(false, string.Join(",", mess), null);
            }

            //由于现在没有打折说法所以没有折后金额
            PaymentAmountModel paymentAmountModel = new PaymentAmountModel()
            {
                CommodityMoney = TotalPrice,
                //没有自营商品情况下，总额就是实际支付金币数
                PaymentAmount = TotalPrice
            };

            //用户赠币不够，需要金币扣减的额度
            decimal giveBuyReduceMoney = 0;

            //有自营商品 并且 用户赠币足够抵扣
            if (SupplyTypeTotalPrice != 0 && user.give_gold>= SupplyTypeTotalPrice)
            {
                //赠币抵扣=自营商品总价
                paymentAmountModel.PreferentialAmount = SupplyTypeTotalPrice;

                //实际金币支付金额=总额-自营商品总额
                paymentAmountModel.PaymentAmount = TotalPrice - SupplyTypeTotalPrice + giveBuyReduceMoney;
            }

            //有自营商品 并且 用户赠币不够抵扣自营商品总额，需要金币支付部分
            if (SupplyTypeTotalPrice != 0 && user.give_gold < SupplyTypeTotalPrice)
            {
                //得到需要金币支付的部分
                giveBuyReduceMoney = SupplyTypeTotalPrice - user.give_gold;

                //实际金币支付金额=原本金币-自营商品总额+赠币不够的额度
                paymentAmountModel.PaymentAmount = TotalPrice- SupplyTypeTotalPrice+ giveBuyReduceMoney;
                //赠币抵扣=用户最大的赠币数量
                paymentAmountModel.PreferentialAmount = user.give_gold;
            }

            return new OperationResult<PaymentAmountModel>(true, "操作成功", paymentAmountModel); ;
        }

        /// <summary>
        /// 创建系统内部订单
        /// </summary>
        /// <param name="submitOrderParams"></param>
        /// <returns></returns>
        /// <remarks>
        /// 修改记录：<br/>        
        /// 2022-04-09：禁用里面的代码，调用 CreateOrder4 的创建订单方法，因为禅道需求286添加的内容根 CreateOrder4 里面的内容是一样的了。
        /// 有一个问题SubmitOrderParams里面没有参数“TableNum”，在 CreateOrder4 的参数中有这个参数，看后续是否在此接口中添加参数“TableNum”
        /// 
        /// </remarks>
        public OperationResult<string> CreateOrder(SubmitOrderParams submitOrderParams)
        {
            var param = submitOrderParams.MapTo<WebChartPreOrderPayDDParams>();
            var data = CreateOrder4(param);
            if (!data.Success) {
                return new OperationResult<string>(false, data.Message);
            }
            return new OperationResult<string>(true, "提交订单成功", data.Data.ParentOrderCode);

            //lock (obj)
            //{                
            //    //下单人信息
            //    T_User user = DBSession.IT_UserDAL.FindSingle(w=>w.user_guid.Equals(submitOrderParams.userid));

            //    //检查商品是否已经有未付款订单
            //    var checkResult = CheckCommodityOrder(submitOrderParams, user.user_id);
            //    if (checkResult.Count > 0)
            //    {
            //        return new OperationResult<string>(false, $"提交订单中有商品已经存在“未付款订单”，请去付款或取消订单后再次下单，商品名称：{string.Join(",", checkResult)}");
            //    }

            //    var commodityIdList = new List<int>();
            //    submitOrderParams.CommodityInfos.ForEach((commodity) => {
            //        commodityIdList.Add(commodity.CommodityId.Value);
            //    });
            //    //检查商品是否已经购买，不允许重复购买
            //    checkResult = CheckCommodityPay(commodityIdList, user.user_id);
            //    if (checkResult.Count > 0)
            //    {
            //        return new OperationResult<string>(false, $"提交订单中有商品已经购买，请不要重复下单，商品名称：{string.Join(",", checkResult)}", null);
            //    }

            //    //如果是从购物车提交的，需要检查购物车里面是否存在
            //    if (submitOrderParams.SubmitType == 0)
            //    {
            //        checkResult = CheckShopping(submitOrderParams, user.user_id);
            //        if (checkResult.Count > 0)
            //        {
            //            return new OperationResult<string>(false, $"从购物车中提交订单，有商品在购物车不存在，商品名称：{string.Join(",", checkResult)}", null);
            //        }
            //    }

            //    //购买商品的详细信息
            //    List<T_DocumentInfo> commodifyInfos = DBSession.IN_OrderDAL.ListDocumentInfo(ListCommodityId(submitOrderParams.CommodityInfos));

            //    //购买商品ID、购买期限、价格
            //    List<PaymentAmountParamsCommodityDetailedInfo> commodifyInfoPrices = DBSession.IN_OrderDAL.ListPayCommodityDetailedInfo(submitOrderParams.CommodityInfos);
            //    if (commodifyInfoPrices.Count == 0) {
            //        return new OperationResult<string>(false,"获取不到商品的价格信息，请管理员检查是否正确设置商品各个期限的价格？");
            //    }

            //    OrderCreate orderCreate = new OrderCreate(DBSession);
            //    string parentOrderCode = orderCreate.NewOrderCode();

            //    //新增订单状态信息
            //    List<N_Order> orders = new List<N_Order>();
            //    //新增订单商品信息
            //    List<N_OrderCommodityInfo> orderCommodityInfos = new List<N_OrderCommodityInfo>();

            //    //当前数量，用于多个商品时生成“商品序号”
            //    int payNum = 1;

            //    foreach (T_DocumentInfo documentInfo in commodifyInfos) {
            //        //当前订单号
            //        string orderCode = parentOrderCode;
            //        //如果购买数量大于1，订单号：父订单号+商品序号
            //        if (submitOrderParams.CommodityInfos.Count > 1) {
            //            orderCode = $"{parentOrderCode}{payNum.ToString().PadLeft(2, '0')}"; ;
            //        }

            //        //购买商品ID、商品期限、价格
            //        PaymentAmountParamsCommodityDetailedInfo paymentAmountParamsCommodityDetailedInfo = commodifyInfoPrices.Find(w=>w.CommodityId==documentInfo.file_id);

            //        //订单状态信息
            //        N_Order order = new N_Order();
            //        order.OrderCode = orderCode;
            //        order.ParentOrderCode = parentOrderCode;
            //        order.OrderNum = orderCreate.OrderNum;
            //        order.OrderState = OrderStateEnum.OrderState1;
            //        order.OrderSource = submitOrderParams.OrderSource;
            //        order.OrderCreateTime = DateTime.Now;
            //        order.OrderCreateUser = user.user_name;
            //        order.OrderCreateUserId = user.user_id;
            //        order.OrderSubmitUser = user.user_name;
            //        order.CommodityMoney = paymentAmountParamsCommodityDetailedInfo.OriPrice;
            //        order.PaymentAmount = paymentAmountParamsCommodityDetailedInfo.OriPrice;
            //        order.PurchasePeriod = paymentAmountParamsCommodityDetailedInfo.PurchasePeriod;
            //        if (submitOrderParams.FolderId != null) {
            //            order.FolderId = submitOrderParams.FolderId;
            //        }
            //        if (submitOrderParams.ShareUserId != null) {
            //            order.ShareUserId = submitOrderParams.ShareUserId;
            //        }
            //        orders.Add(order);

            //        //订单商品信息
            //        N_OrderCommodityInfo orderCommodityInfo = documentInfo.MapTo<N_OrderCommodityInfo>();
            //        orderCommodityInfo.OrderCode = orderCode;
            //        orderCommodityInfos.Add(orderCommodityInfo) ;

            //        payNum++;
            //    }

            //    N_OrderNumber orderNumber = new N_OrderNumber() {
            //        OrderNum = orderCreate.OrderNum,
            //        CreateTime = DateTime.Now
            //    };

            //    //组装商品ID
            //    var fileid = new List<int>();
            //    submitOrderParams.CommodityInfos.ForEach((CommodityInfo) => { fileid.Add(CommodityInfo.CommodityId.Value); });

            //    HCQ2_IBLL.IUnitWork unitWork = SpringHelper.GetObject<HCQ2_IBLL.IUnitWork>("BllUnitWork");
            //    unitWork.BatchAdd<N_Order>(orders.ToArray());
            //    unitWork.BatchAdd<N_OrderCommodityInfo>(orderCommodityInfos.ToArray());
            //    unitWork.Add<N_OrderNumber>(orderNumber);

            //    //从购物车下单，需要删除购物车中商品
            //    if (submitOrderParams.SubmitType == 0)
            //    {
            //        submitOrderParams.CommodityInfos.ForEach((CommodityInfo) => {
            //            var shopp = DBSession.IN_ShoppingDAL.FindSingle(w => w.FileId == CommodityInfo.CommodityId.Value && w.UserId == user.user_id);
            //            unitWork.Delete<N_Shopping>(shopp);
            //        });
            //    }

            //    unitWork.Save();

            //    return new OperationResult<string>(true,"提交订单成功", parentOrderCode);
            //}
        }
       
        public OperationResult<CreateOrder2Model> CreateOrder3(SubmitOrderParams submitOrderParams)
        {
            lock (obj)
            {
                //下单人信息
                T_User user = DBSession.IT_UserDAL.FindSingle(w => w.user_guid.Equals(submitOrderParams.userid));

                //检查商品是否已经有未付款订单
                var checkResult = CheckCommodityOrder(submitOrderParams, user.user_id);
                if (checkResult.Count > 0)
                {
                    return new OperationResult<CreateOrder2Model>(false, $"提交订单中有商品已经存在“未付款订单”，请去付款或取消订单后再次下单，商品名称：{string.Join(",", checkResult)}");
                }

                var commodityIdList = new List<int>();
                submitOrderParams.CommodityInfos.ForEach((commodity) => {
                    commodityIdList.Add(commodity.CommodityId.Value);
                });
                //检查商品是否已经购买，不允许重复购买
                checkResult = CheckCommodityPay(commodityIdList, user.user_id);
                if (checkResult.Count > 0)
                {
                    return new OperationResult<CreateOrder2Model>(false, $"提交订单中有商品已经购买，请不要重复下单，商品名称：{string.Join(",", checkResult)}", null);
                }

                //如果是从购物车提交的，需要检查购物车里面是否存在
                if (submitOrderParams.SubmitType == 0)
                {
                    checkResult = CheckShopping(submitOrderParams, user.user_id);
                    if (checkResult.Count > 0)
                    {
                        return new OperationResult<CreateOrder2Model>(false, $"从购物车中提交订单，有商品在购物车不存在，商品名称：{string.Join(",", checkResult)}", null);
                    }
                }

                //购买商品的详细信息
                List<T_DocumentInfo> commodifyInfos = DBSession.IN_OrderDAL.ListDocumentInfo(ListCommodityId(submitOrderParams.CommodityInfos));

                //购买商品ID、购买期限、价格
                List<PaymentAmountParamsCommodityDetailedInfo> commodifyInfoPrices = DBSession.IN_OrderDAL.ListPayCommodityDetailedInfo(submitOrderParams.CommodityInfos);
                if (commodifyInfoPrices.Count == 0)
                {
                    return new OperationResult<CreateOrder2Model>(false, "获取不到商品的价格信息，请管理员检查是否正确设置商品各个期限的价格？");
                }

                OrderCreate orderCreate = new OrderCreate(DBSession);
                string parentOrderCode = orderCreate.NewOrderCode();

                //新增订单状态信息
                List<N_Order> orders = new List<N_Order>();
                //新增订单商品信息
                List<N_OrderCommodityInfo> orderCommodityInfos = new List<N_OrderCommodityInfo>();

                //当前数量，用于多个商品时生成“商品序号”
                int payNum = 1;

                //总价
                decimal totalPrice = 0;

                foreach (T_DocumentInfo documentInfo in commodifyInfos)
                {
                    //当前订单号
                    string orderCode = parentOrderCode;
                    //如果购买数量大于1，订单号：父订单号+商品序号
                    if (submitOrderParams.CommodityInfos.Count > 1)
                    {
                        orderCode = $"{parentOrderCode}{payNum.ToString().PadLeft(2, '0')}"; ;
                    }

                    //购买商品ID、商品期限、价格
                    PaymentAmountParamsCommodityDetailedInfo paymentAmountParamsCommodityDetailedInfo = commodifyInfoPrices.Find(w => w.CommodityId == documentInfo.file_id);

                    //订单状态信息
                    N_Order order = new N_Order();
                    order.OrderCode = orderCode;
                    order.ParentOrderCode = parentOrderCode;
                    order.OrderNum = orderCreate.OrderNum;
                    order.OrderState = OrderStateEnum.OrderState1;
                    order.OrderSource = submitOrderParams.OrderSource;
                    order.OrderCreateTime = DateTime.Now;
                    order.OrderCreateUser = user.user_name;
                    order.OrderCreateUserId = user.user_id;
                    order.OrderSubmitUser = user.user_name;
                    order.CommodityMoney = paymentAmountParamsCommodityDetailedInfo.OriPrice;
                    order.PaymentAmount = paymentAmountParamsCommodityDetailedInfo.OriPrice;
                    order.PurchasePeriod = paymentAmountParamsCommodityDetailedInfo.PurchasePeriod;
                    if (submitOrderParams.FolderId != null)
                    {
                        order.FolderId = submitOrderParams.FolderId;
                    }
                    if (submitOrderParams.ShareUserId != null)
                    {
                        order.ShareUserId = submitOrderParams.ShareUserId;
                    }
                    orders.Add(order);

                    //订单商品信息
                    N_OrderCommodityInfo orderCommodityInfo = documentInfo.MapTo<N_OrderCommodityInfo>();
                    orderCommodityInfo.OrderCode = orderCode;
                    orderCommodityInfos.Add(orderCommodityInfo);

                    payNum++;

                    totalPrice += paymentAmountParamsCommodityDetailedInfo.OriPrice;
                }

                N_OrderNumber orderNumber = new N_OrderNumber()
                {
                    OrderNum = orderCreate.OrderNum,
                    CreateTime = DateTime.Now
                };

                //组装商品ID
                var fileid = new List<int>();
                submitOrderParams.CommodityInfos.ForEach((CommodityInfo) => { fileid.Add(CommodityInfo.CommodityId.Value); });

                HCQ2_IBLL.IUnitWork unitWork = SpringHelper.GetObject<HCQ2_IBLL.IUnitWork>("BllUnitWork");
                unitWork.BatchAdd<N_Order>(orders.ToArray());
                unitWork.BatchAdd<N_OrderCommodityInfo>(orderCommodityInfos.ToArray());
                unitWork.Add<N_OrderNumber>(orderNumber);

                //从购物车下单，需要删除购物车中商品
                if (submitOrderParams.SubmitType == 0)
                {
                    submitOrderParams.CommodityInfos.ForEach((CommodityInfo) => {
                        var shopp = DBSession.IN_ShoppingDAL.FindSingle(w => w.FileId == CommodityInfo.CommodityId.Value && w.UserId == user.user_id);
                        unitWork.Delete<N_Shopping>(shopp);
                    });
                }

                unitWork.Save();

                return new OperationResult<CreateOrder2Model>(true, "提交订单成功", new CreateOrder2Model() { 
                    ParentOrderCode = parentOrderCode,
                    CommodityMoney = totalPrice
                });
            }
        }

        /// <summary>
        /// 创建系统内部订单，因为需求《VLions需求规格_度度圈接口需求_订单及购物车-202100909.docx》直接复制的CreateOrder3代码添加了，文档中的新增参数到订单中
        /// </summary>
        /// <param name="submitOrderParams"></param>
        /// <returns></returns>
        /// <remarks>
        /// 修改记录：<br/>
        /// 2021-10-17：因度度圈和美碗下单支付可以同商品购买多个添加，订单信息的单价，原商品金额采用 单价*购买数量
        /// 2021-10-20：取消实物商品限制：有未付款订单和已购买不让下单
        /// 2022-06-05：实物商品需要按照规格来获取价格，需求从微信交流群中发出。
        /// 
        /// </remarks>
        public OperationResult<CreateOrder2Model> CreateOrder4(WebChartPreOrderPayDDParams submitOrderParams)
        {
            lock (obj)
            {
                //下单人信息
                T_User user = DBSession.IT_UserDAL.FindSingle(w => w.user_guid.Equals(submitOrderParams.userid));

                //购买商品的详细信息
                List<T_DocumentInfo> commodifyInfos = DBSession.IN_OrderDAL.ListDocumentInfo(ListCommodityId(submitOrderParams.CommodityInfos));

                //提交的商品列表中，是否存在虚拟商品，true存在虚拟商品
                bool fictitious = CheckFictitiousCommodity(commodifyInfos);
                if (fictitious)
                {
                    //检查商品是否已经有未付款订单，虚拟商品需要此检查，实物商品不用此检查
                    var checkResult = CheckCommodityOrder(submitOrderParams, user.user_id);
                    if (checkResult.Count > 0)
                    {
                        return new OperationResult<CreateOrder2Model>(false, $"提交订单中有商品已经存在“未付款订单”，请去付款或取消订单后再次下单，商品名称：{string.Join(",", checkResult)}");
                    }

                    //商品ID集合
                    var commodityIdList = submitOrderParams.CommodityInfos.Select(c => c.CommodityId.Value).ToList();

                    //检查商品是否已经购买，不允许重复购买，虚拟商品需要此检查，实物商品不用此检查
                    checkResult = CheckCommodityPay(commodityIdList, user.user_id);
                    if (checkResult.Count > 0)
                    {
                        return new OperationResult<CreateOrder2Model>(false, $"提交订单中有商品已经购买，请不要重复下单，商品名称：{string.Join(",", checkResult)}", null);
                    }
                }                

                //如果是从购物车提交的，需要检查购物车里面是否存在
                if (submitOrderParams.SubmitType == 0)
                {
                    var checkShoppingResult = CheckShopping(submitOrderParams, user.user_id);
                    if (checkShoppingResult.Count > 0)
                    {
                        return new OperationResult<CreateOrder2Model>(false, $"从购物车中提交订单，有商品在购物车不存在，商品名称：{string.Join(",", checkShoppingResult)}", null);
                    }
                }                

                //购买商品ID、购买期限、价格
                List<PaymentAmountParamsCommodityDetailedInfo> commodifyInfoPrices = DBSession.IN_OrderDAL.ListPayCommodityDetailedInfo(submitOrderParams.CommodityInfos);
                if (commodifyInfoPrices.Count == 0)
                {
                    return new OperationResult<CreateOrder2Model>(false, "获取不到商品的价格信息，请管理员检查是否正确设置商品各个期限的价格？");
                }

                //创建订单号
                OrderCreate orderCreate = new OrderCreate(DBSession);
                string parentOrderCode = orderCreate.NewOrderCode();

                //商品名称
                List<string> commodityNames = new List<string>();
                //新增订单状态信息
                List<N_Order> orders = new List<N_Order>();
                
                //新增订单商品信息
                List<N_OrderCommodityInfo> orderCommodityInfos = new List<N_OrderCommodityInfo>();

                //2021-9-16：禅道172号需求添加规格列表
                List<N_Spec> specs = new List<N_Spec>();

                //当前数量，用于多个商品时生成“商品序号”
                int payNum = 1;

                //需要支付的总价
                decimal totalPrice = 0;

                //创建，订单及订单商品信息，用于保存
                foreach (T_DocumentInfo documentInfo in commodifyInfos)
                {
                    //当前订单号
                    string orderCode = parentOrderCode;
                    //如果购买数量大于1，订单号：父订单号+商品序号
                    if (submitOrderParams.CommodityInfos.Count > 1)
                    {
                        orderCode = $"{parentOrderCode}{payNum.ToString().PadLeft(2, '0')}"; ;
                    }

                    //获取提交商品的购买数量；2021-10-17，因度度圈和美碗下单支付可以同商品购买多个添加
                    int quantity = submitOrderParams.CommodityInfos.Find(w => w.CommodityId.Value == documentInfo.file_id).Quantity;

                    //购买商品ID、商品期限、价格
                    PaymentAmountParamsCommodityDetailedInfo paymentAmountParamsCommodityDetailedInfo = commodifyInfoPrices.Find(w => w.CommodityId == documentInfo.file_id);

                    //商品名称
                    commodityNames.Add(documentInfo.file_name);

                    //订单状态信息
                    N_Order order = new N_Order();
                    order.OrderCode = orderCode;
                    order.ParentOrderCode = parentOrderCode;
                    order.OrderNum = orderCreate.OrderNum;
                    order.OrderState = OrderStateEnum.OrderState1;
                    order.OrderSource = submitOrderParams.OrderSource;
                    order.OrderCreateTime = DateTime.Now;
                    order.OrderCreateUser = user.user_name;
                    order.OrderCreateUserId = user.user_id;
                    order.OrderSubmitUser = user.user_name;
                    //商品金额
                    order.CommodityMoney = paymentAmountParamsCommodityDetailedInfo.OriPrice * quantity;
                    //商品单价；2021-10-17，因度度圈和美碗下单支付可以同商品购买多个添加
                    order.UnitPrice = paymentAmountParamsCommodityDetailedInfo.OriPrice;                                
                    //实付金额
                    order.PaymentAmount = paymentAmountParamsCommodityDetailedInfo.OriPrice * quantity;
                    //购买期限
                    order.PurchasePeriod = paymentAmountParamsCommodityDetailedInfo.PurchasePeriod;
                    if (submitOrderParams.FolderId != null)
                    {
                        order.FolderId = submitOrderParams.FolderId;

                        //商铺ID，不为空才计算折扣价格，因为计算需要商铺ID

                        ////用户等级
                        UserLevelColumn userLevelColumn = bLLSession.T_VRUserLevel.ResetUserLevel(user.user_id, submitOrderParams.FolderId.Value, DateTime.Now.Year);
                        ////商品折扣
                        decimal rate = bLLSession.T_VRUserLevel.GetGoodRate(userLevelColumn.userLevel, documentInfo.file_id, submitOrderParams.FolderId.Value);
                        ////商品打折后的金额，当折扣大于0才计算，否则金额为0
                        if (rate > 0)
                        {
                            decimal rateMoney = Math.Round(paymentAmountParamsCommodityDetailedInfo.OriPrice * rate / 100, 2);

                            ////折后金额 乘数量的最终价格
                            order.DiscountMoney = rateMoney * quantity;

                            ////实付金额，如果有折后金额计算，那么就是折后金额
                            order.PaymentAmount = order.DiscountMoney;
                        }
                    }

                    //检查商品是否实物商品？如果是实物商品并且有规格，那么获取规格的价格
                    if (documentInfo.isEntity) {
                        var paramsCommodity = submitOrderParams.CommodityInfos.FirstOrDefault(w => w.CommodityId == documentInfo.file_id);
                        //有传入规格
                        if (paramsCommodity.Specs != null && paramsCommodity.Specs.Count > 0) {
                            //找规格对应的价格
                            foreach (SpecParamModel spec in paramsCommodity.Specs)
                            {
                                //规格ID为空直接跳过
                                if (spec.OptionId == null)
                                {
                                    continue;
                                }
                                //通过规格去获取规格的价格
                                var cost = GetSpecMoney(documentInfo.file_id, spec.OptionId.Value);
                                //规格价格的总价：规格价格*购买数量
                                var amount = cost * quantity;

                                //商品金额
                                order.CommodityMoney = amount;
                                //商品单价
                                order.UnitPrice = cost;

                                ////折后金额
                                order.DiscountMoney = amount;

                                ////实付金额
                                order.PaymentAmount = amount;
                            }                          
                        }
                    }


                    if (submitOrderParams.ShareUserId != null)
                    {
                        order.ShareUserId = submitOrderParams.ShareUserId;
                    }

                    #region 需求《VLions需求规格_度度圈接口需求_订单及购物车-202100909.docx》新增的内容

                    order.TableNum = submitOrderParams.TableNum;
                    order.Name = submitOrderParams.Name;
                    order.Phone = submitOrderParams.Phone;
                    order.Area = submitOrderParams.Area;
                    order.Address = submitOrderParams.Address;
                    order.OrderType = submitOrderParams.OrderType;
                    order.PackType = submitOrderParams.PackType == null ? 0 : submitOrderParams.PackType.Value;
                    //0=待备货（默认值）、1=备货中、2=备货完成、3=已发货
                    order.StorageStatus = 0;
                    order.Quantity = quantity;
                    #endregion

                    //禅道需求226，增加参数
                    order.GpsX = submitOrderParams.GpsX;
                    order.GpsY = submitOrderParams.GpsY;

                    orders.Add(order);

                    //订单商品信息
                    N_OrderCommodityInfo orderCommodityInfo = documentInfo.MapTo<N_OrderCommodityInfo>();
                    orderCommodityInfo.OrderCode = orderCode;
                    orderCommodityInfo.StoreID = documentInfo.store_id;
                    orderCommodityInfo.Quantity = quantity;
                    orderCommodityInfos.Add(orderCommodityInfo);

                    payNum++;

                    //累加价格到总价上面
                    totalPrice += order.PaymentAmount.Value;

                    #region 2021-9-16：禅道172号需求添加规格列表

                    //通过商品ID找到提交参数中的购买商品的 规格列表
                    PaymentAmountParamsCommodityInfo commodityInfo = submitOrderParams.CommodityInfos.Find(w => w.CommodityId.Value == paymentAmountParamsCommodityDetailedInfo.CommodityId);
                    if (commodityInfo.Specs != null && commodityInfo.Specs.Count > 0)
                    {
                        foreach (var s in commodityInfo.Specs)
                        {
                            N_Spec spec = new N_Spec();
                            //1订单的
                            spec.SpecType = 1;
                            spec.OrderCode = orderCode;
                            spec.SpecName = s.SpecName;
                            spec.SpecValue = s.SpecValue;
                            spec.OptionId = s.OptionId;
                            specs.Add(spec);
                        }
                    }
                    #endregion
                }

                N_OrderNumber orderNumber = new N_OrderNumber()
                {
                    OrderNum = orderCreate.OrderNum,
                    CreateTime = DateTime.Now
                };
                
                HCQ2_IBLL.IUnitWork unitWork = SpringHelper.GetObject<HCQ2_IBLL.IUnitWork>("BllUnitWork");
                unitWork.BatchAdd<N_Order>(orders.ToArray());
                unitWork.BatchAdd<N_OrderCommodityInfo>(orderCommodityInfos.ToArray());
                unitWork.Add<N_OrderNumber>(orderNumber);
                //商品规格列表有数据，那么执行插入
                if (specs != null && specs.Count > 0)
                {
                    unitWork.BatchAdd<N_Spec>(specs.ToArray());
                }
                //从购物车下单，需要删除购物车中商品
                if (submitOrderParams.SubmitType == 0)
                {
                    submitOrderParams.CommodityInfos.ForEach((CommodityInfo) => {
                        var shopp = DBSession.IN_ShoppingDAL.FindSingle(w => w.FileId == CommodityInfo.CommodityId.Value && w.UserId == user.user_id);
                        unitWork.Delete<N_Shopping>(shopp);
                    });
                }

                unitWork.Save();

                return new OperationResult<CreateOrder2Model>(true, "提交订单成功", new CreateOrder2Model()
                {
                    ParentOrderCode = parentOrderCode,
                    CommodityMoney = totalPrice,
                    CommodityNames = string.Join(",", commodityNames)
                });
            }
        }

        /// <summary>
        /// 获取规格对应的价格
        /// </summary>
        /// <param name="commodityId">商品ID</param>
        /// <param name="specOptionId">规格ID</param>
        /// <returns></returns>
        public decimal GetSpecMoney(int commodityId, int specOptionId) {
            //获取规格对应的价格
            string sql = $"select top 1 specMoney from T_VRDDSpecPrice where groupCode in (select groupCode from T_VRDDSpecGroupPrice where fileId={commodityId} and optionID={specOptionId})";
            //商品规格的价格
            Object obj = SqlHelper.ExecuteScalar(sql);
            if (obj != null)
            {
                //返回规格价格
                return Convert.ToDecimal(obj);
            }
            return 0;
        }

        public OperationResult<CreateOrder2Model> CreateOrder2(CreateOrder2Params order2Params)
        {
            lock (obj2)
            {
                try
                {
                    //下单人信息
                    T_User user = DBSession.IT_UserDAL.FindSingle(w => w.user_guid.Equals(order2Params.userid));

                    //验证设备是否正在使用中
                    //if (CheckDeviceRun(user.user_id, order2Params.CommodityId.Value))
                    //{
                    //    return new OperationResult<CreateOrder2Model>(false, "设备正在使用中，请等使用完毕再购买", null);
                    //}
                    //验证设备是否正在使用中
                    if (CheckDevice24TermOfValidity(user.user_id, order2Params.CommodityId.Value))
                    {
                        return new OperationResult<CreateOrder2Model>(false, "该设备已支付，欢迎体验", null);
                    }
                    

                    //购买商品的详细信息
                    List<T_DocumentInfo> commodifyInfos = DBSession.IN_OrderDAL.ListDocumentInfo(new List<int>() { order2Params.CommodityId.Value });
                    if (commodifyInfos == null || commodifyInfos.Count == 0)
                    {
                        return new OperationResult<CreateOrder2Model>(false, "获取不到商品的信息");
                    }

                    //购买商品ID、购买期限、价格
                    T_VRGoodDisiPrice disiPrice = GetPriceInfo(order2Params.PurchasePeriodCode);
                    if (disiPrice == null)
                    {
                        return new OperationResult<CreateOrder2Model>(false, "获取不到商品的价格信息");
                    }

                    //创建订单号
                    OrderCreate orderCreate = new OrderCreate(DBSession);
                    string parentOrderCode = orderCreate.NewOrderCode();

                    //新增订单状态信息
                    N_Order order = new N_Order();
                    order.OrderCode = parentOrderCode;
                    order.ParentOrderCode = parentOrderCode;
                    order.OrderNum = orderCreate.OrderNum;
                    order.OrderState = OrderStateEnum.OrderState1;
                    order.OrderSource = order2Params.OrderSource;
                    order.OrderCreateTime = DateTime.Now;
                    order.OrderCreateUser = user.user_name;
                    order.OrderCreateUserId = user.user_id;
                    order.OrderSubmitUser = user.user_name;
                    order.CommodityMoney = disiPrice.ori_price;
                    order.PaymentAmount = disiPrice.ori_price;
                    order.PurchasePeriod = disiPrice.op_month;

                    //新增订单商品信息
                    N_OrderCommodityInfo orderCommodityInfo = commodifyInfos[0].MapTo<N_OrderCommodityInfo>();
                    orderCommodityInfo.OrderCode = parentOrderCode;

                    N_OrderNumber orderNumber = new N_OrderNumber()
                    {
                        OrderNum = orderCreate.OrderNum,
                        CreateTime = DateTime.Now
                    };


                    HCQ2_IBLL.IUnitWork unitWork = SpringHelper.GetObject<HCQ2_IBLL.IUnitWork>("BllUnitWork");
                    unitWork.Add<N_Order>(order);
                    unitWork.Add<N_OrderCommodityInfo>(orderCommodityInfo);
                    unitWork.Add<N_OrderNumber>(orderNumber);

                    unitWork.Save();

                    return new OperationResult<CreateOrder2Model>(true, "提交订单成功", new CreateOrder2Model()
                    {
                        ParentOrderCode = parentOrderCode,
                        CommodityMoney = disiPrice.ori_price
                    });
                }
                catch (Exception e) {
                    LogHelper.ErrorLog("系统内部创建订单失败",typeof(N_Order),e);
                    return new OperationResult<CreateOrder2Model>(false, "系统内部创建订单失败");
                }
            }
        }

        public OperationResult<WebChartPreOrderPayDDQRCodeResultModel> WebChartQRCodePayOrder(WebChartQRCodePayOrderParams paymentParams)
        {
            lock (obj3) {
                //请求用户
                T_User user = DBSession.IT_UserDAL.FindSingle(w => w.user_guid.Equals(paymentParams.userid));

                //通过父单号获取所有订单信息
                List<N_Order> orders = DBSession.IN_OrderDAL.Select(w => w.ParentOrderCode.Equals(paymentParams.ParentOrderCode));
                if (orders.Count == 0)
                {
                    return new OperationResult<WebChartPreOrderPayDDQRCodeResultModel>(false, $"未找到订单：{paymentParams.ParentOrderCode} 的信息", null);
                }

                //订单状态不是：未付款
                if (orders[0].OrderState != OrderStateEnum.OrderState1)
                {
                    return new OperationResult<WebChartPreOrderPayDDQRCodeResultModel>(false, $"只有订单状态为“未付款”才能支付订单，当前状态：{OrderStateEnum.GetOrderStateName(orders[0].OrderState)} ", null);
                }

                //总价
                decimal totalPrice = 0;
                foreach (N_Order order in orders) {
                    //累加价格到总价上面
                    totalPrice += order.PaymentAmount.Value;
                }

                if (totalPrice == 0)
                {
                    return new OperationResult<WebChartPreOrderPayDDQRCodeResultModel>(false, "订单计算后的实付金额为：0，不调用微信支付接口生成二维码");
                }

                //调用微信二维码支付接口，创建二维码 得到二维码显示地址            
                OperationResult<string> execWechatResult = ExecWechatQRCode(paymentParams.ParentOrderCode, totalPrice);
                if (!execWechatResult.Success)
                {
                    return new OperationResult<WebChartPreOrderPayDDQRCodeResultModel>(false, "调用微信支付接口失败：" + execWechatResult.Message);
                }

                return new OperationResult<WebChartPreOrderPayDDQRCodeResultModel>(true, "操作成功，请用微信扫二维码进行支付。", new WebChartPreOrderPayDDQRCodeResultModel()
                {
                    QRCodeWebUrl = execWechatResult.Data,
                    ParentOrderCode = paymentParams.ParentOrderCode
                });
            }
        }


        public OperationResult<PayOrderModel> PayOrder(PaymentParams paymentParams)
        {            
            lock (obj1)
            {
                T_User user = DBSession.IT_UserDAL.FindSingle(w => w.user_guid.Equals(paymentParams.userid));

                //获得商品ID和购买期限
                List<PaymentAmountParamsCommodityInfo> commodityIds = OrderDAL.ListPaymentAmountParamsCommodityInfo(paymentParams.ParentOrderCode);
                if (commodityIds == null || commodityIds.Count == 0) {
                    return new OperationResult<PayOrderModel>(false,$"未找到父单号：{paymentParams.ParentOrderCode}的相关信息",null);
                }

                var commodityIdList = new List<int>();
                commodityIds.ForEach((commodity)=> {
                    commodityIdList.Add(commodity.CommodityId.Value);
                });
                //检查商品是否已经购买，不允许重复购买
                var checkResult = CheckCommodityPay(commodityIdList, user.user_id);
                if (checkResult.Count > 0)
                {
                    return new OperationResult<PayOrderModel>(false,$"付款订单中有商品已经购买，请不要重复购买，商品名称：{string.Join(",",checkResult)}",null);
                }

                //获取支付总价,支付金额信息
                OperationResult<PaymentAmountModel> operationResult = GetPaymentAmount(new PaymentAmountParams() { 
                    CommodityIds = commodityIds,
                    userid = paymentParams.userid
                });
                if (!operationResult.Success)
                {
                    return new OperationResult<PayOrderModel>(false, operationResult.Message,null);
                }

                PaymentAmountModel paymentAmountModel = operationResult.Data;
                if (paymentAmountModel == null)
                {
                    return new OperationResult<PayOrderModel>(false, "无法获取到支付金额信息",null);
                }

                //验证用户金币是否足够                                
                decimal beforeBuy = user.buy_gold;//扣减前金币数量
                decimal beforeGive = user.give_gold;//扣减前赠币数量
                decimal buyReduceMoney = 0;//扣减金币数量
                decimal giveReduceMoney = 0;//扣减赠币数量
                decimal giveBuyReduceMoney = 0;//赠币不够，需要金币扣减的额度
                if (!CheckUserMoney(paymentAmountModel,ref user, ref buyReduceMoney,ref giveReduceMoney,ref giveBuyReduceMoney))
                {
                    return new OperationResult<PayOrderModel>(false, "金币赠币余额不足", null);
                }

                //通过父单号获取所有订单信息
                List<N_Order> orders = DBSession.IN_OrderDAL.Select(w => w.ParentOrderCode.Equals(paymentParams.ParentOrderCode));
                if (orders.Count == 0)
                {
                    return new OperationResult<PayOrderModel>(false, $"未找到订单：{paymentParams.ParentOrderCode} 的信息", null);
                }

                //订单状态不是：未付款
                if (orders[0].OrderState!=OrderStateEnum.OrderState1)
                {
                    return new OperationResult<PayOrderModel>(false, $"只有订单状态为“未付款”才能支付订单，当前状态：{OrderStateEnum.GetOrderStateName(orders[0].OrderState)} ", null);
                }
                
                //金币
                T_VRGoldLog _VRGoldLog = new T_VRGoldLog() {
                    user_id = user.user_id,
                    user_name = user.user_name,
                    unit_code = user.unit_code,
                    gold_num = paymentAmountModel.CommodityMoney,
                    gold_type = 1,//金币
                    operator_type = 2,
                    create_id = user.user_id,
                    create_name = user.user_name,
                    create_date = DateTime.Now,
                    ParentOrderCode = paymentParams.ParentOrderCode,

                    BeforBuyGold = beforeBuy,//变动前金币
                    BeforGiveGold = beforeGive,//变动前赠币
                    SubtractBuyGold = buyReduceMoney,//金币支付金额
                    SubtractGiveGold = giveReduceMoney,//增币支付金额
                    BuyGold = user.buy_gold,//扣减后用户金币
                    GiveGold = user.give_gold,//扣减后用户赠币
                    TotalMoney = paymentAmountModel.CommodityMoney//购买商品总价                                       
                };
                //赠币；2020-4-23谭要求修改为两条区分金币赠币，界面只要变动前后两个。
                T_VRGoldLog _VRGoldLog1 = new T_VRGoldLog()
                {
                    user_id = user.user_id,
                    user_name = user.user_name,
                    unit_code = user.unit_code,
                    gold_num = paymentAmountModel.CommodityMoney,
                    gold_type = 2,//赠币
                    operator_type = 2,
                    create_id = user.user_id,
                    create_name = user.user_name,
                    create_date = DateTime.Now,
                    ParentOrderCode = paymentParams.ParentOrderCode,

                    BeforBuyGold = beforeBuy,//变动前金币
                    BeforGiveGold = beforeGive,//变动前赠币
                    SubtractBuyGold = buyReduceMoney,//金币支付金额
                    SubtractGiveGold = giveReduceMoney,//增币支付金额
                    BuyGold = user.buy_gold,//扣减后用户金币
                    GiveGold = user.give_gold,//扣减后用户赠币
                    TotalMoney = paymentAmountModel.CommodityMoney//购买商品总价                                       
                };

                if (giveBuyReduceMoney > 0)
                {
                    _VRGoldLog.Content = $"用户：{user.user_name} 下单付款总额：{paymentAmountModel.CommodityMoney}，其中扣减金币：{buyReduceMoney}，包含赠币不够支付使用金币支付额度：{giveBuyReduceMoney}，扣减赠币：{giveReduceMoney}，购买：{commodityIds.Count}件商品，父订单编号：{paymentParams.ParentOrderCode}";                    
                }
                else {
                    _VRGoldLog.Content = $"用户：{user.user_name} 下单付款总额：{paymentAmountModel.CommodityMoney}，其中扣减金币：{buyReduceMoney}，扣减赠币：{giveReduceMoney} 购买：{commodityIds.Count}件商品，父订单编号：{paymentParams.ParentOrderCode}";
                }
                _VRGoldLog1.Content = _VRGoldLog.Content;

                using (TransactionScope transactionScope = new TransactionScope())
                {
                    foreach (N_Order order in orders)
                    {
                        //修改订单付款方式
                        order.PaymentMethod = paymentParams.PayMethod;
                        //修改订单状态
                        order.OrderState = OrderStateEnum.OrderState2;
                        //修改付款时间
                        order.PaymentTime = DateTime.Now;
                        //根据当前时间和购买期限计算截止时间
                        if(order.PurchasePeriod.Value>0)
                            order.EndTime = DateTime.Now.AddMonths(order.PurchasePeriod.Value);
                        else
                            order.EndTime = DateTime.Now.AddYears(100);
                    }

                    DBSession.IT_UserDAL.Modify(user,w=>w.user_id==user.user_id, "buy_gold", "give_gold");

                    //20200429添加，只有扣减了才会记录日志
                    if (_VRGoldLog.SubtractBuyGold > 0)
                    {
                        DBSession.IT_VRGoldLogDAL.Add(_VRGoldLog);
                    }
                    if (_VRGoldLog1.SubtractGiveGold > 0) {
                        DBSession.IT_VRGoldLogDAL.Add(_VRGoldLog1);
                    }
                    
                    transactionScope.Complete();
                }

                var payDocFileOptions = DBSession.IT_VRShoppingCartDAL.ListPayDocFileOptionsModel(paymentParams.ParentOrderCode);

                PayOrderModel payOrderModel = new PayOrderModel()
                {
                    ParentOrderCode = paymentParams.ParentOrderCode,
                    OrderState = OrderStateEnum.OrderState2,
                    PayDocFileOptions = payDocFileOptions
                };
                return new OperationResult<PayOrderModel>(true, "支付成功", payOrderModel);
            }
        }
        
        public IList<string> CheckCommodityPay(List<int> commodityIds,int userId)
        {
            var result = new List<string>();

            commodityIds.ForEach((commodityId)=> {
                string isPayFileName = OrderDAL.CheckCommodityPay(userId,commodityId);

                if (!string.IsNullOrEmpty(isPayFileName))
                {
                    result.Add(isPayFileName);
                }                
            });

            return result;
        }
        
        public OperationResult ConfirmOrder(OrderConfirmParams cancelConfirmParams)
        {
            N_Order dbOrder = OrderDAL.FindSingle(w=>w.OrderCode.Equals(cancelConfirmParams.OrderCode));
            if (dbOrder == null) {
                return new OperationResult(false,$"没有找到订单号：{cancelConfirmParams.OrderCode}的相关信息");
            }
            if (dbOrder.OrderState != OrderStateEnum.OrderState2)
            {
                return new OperationResult(false, $"只有订单状态为“买家已付款”才能确认订单，当前状态为“{OrderStateEnum.GetOrderStateName(dbOrder.OrderState)}”");
            }

            T_User user = DBSession.IT_UserDAL.FindSingle(w=>w.user_guid.Equals(cancelConfirmParams.userid));

            N_OrderLog orderLog = new N_OrderLog()
            {
                OrderCode = cancelConfirmParams.OrderCode,
                ParentOrderCode = dbOrder.ParentOrderCode,
                CreateTime = DateTime.Now,
                UserId = user.user_id,
                Content = $"用户：{user.user_name} 确认订单成功,订单编号：{cancelConfirmParams.OrderCode}"
            };
            N_Order order = new N_Order()
            {
                OrderState = OrderStateEnum.OrderState4,
                ConfirmTime = DateTime.Now
            };
           
            using (TransactionScope transactionScope = new TransactionScope())
            {
                DBSession.IN_OrderLogDAL.Add(orderLog);
                DBSession.IN_OrderDAL.Modify(order, w => w.OrderCode.Equals(cancelConfirmParams.OrderCode), "OrderState", "ConfirmTime");

                transactionScope.Complete();
            }
            return new OperationResult(true, "确认订单成功");
        }
        
        public OperationResult CancelOrder(OrderCancelParams orderCancelParams)
        {
            //获取订单当前状态
            Nullable<int> orderState = OrderDAL.GetOrderState(orderCancelParams.ParentOrderCode);
            if (orderState !=  null && orderState.Value != OrderStateEnum.OrderState1) {
                return new OperationResult(false,$"只有订单状态为“待付款”才能取消订单，当前订单状态：{OrderStateEnum.GetOrderStateName(orderState.Value)}");
            }

            OrderDAL.CancelOrder(orderCancelParams.ParentOrderCode);

            return new OperationResult(true,"取消订单成功");
        }
        
        public DataTable ListOrderListExpData(GetPcOrderListParams listParams)
        {
            return OrderDAL.ListOrderListExpData(listParams);
        }
        
        public int GetOrderTotal(GetOrderTotalParams getOrderTotalParams)
        {
            return OrderDAL.GetOrderTotal(getOrderTotalParams);
        }

        /// <summary>
        /// 获取OpenId
        /// </summary>
        /// <param name="code">小程序获得的代码</param>
        /// <param name="webChartAppId">对应小程序AppId</param>
        /// <returns></returns>
        /// <remarks>
        /// 修改记录：
        /// 2021-10-7：添加参数webChartAppId，如果不为空，那么去数据库中获取对应的密钥进行openId的获取
        /// </remarks>
        public OperationResult<ChartUser> GetWebChartOpenId(string code, string webChartAppId = null)
        {
            try
            {
                string appId = ConfigurationHelper.AppSetting("appId");
                string appSecret = ConfigurationHelper.AppSetting("appSecret");

                //2021-10-7，添加，根据传入appId获取对应密钥
                if (!string.IsNullOrEmpty(webChartAppId))
                {
                    appId = webChartAppId;
                    appSecret = GetAppSecret(webChartAppId);
                    if (string.IsNullOrEmpty(appSecret)) {
                        return new OperationResult<ChartUser>(false, "获取微信openid失败：通过appId=" + webChartAppId+"未找到对应的密钥配置，请检查");
                    }
                }

                string serviceAddress = "https://api.weixin.qq.com/sns/jscode2session?";
                serviceAddress = $"{serviceAddress}appid={appId}&secret={appSecret}";
                serviceAddress = $"{serviceAddress}&js_code={code}&grant_type=authorization_code";

                LogHelper.InfoLog(typeof(N_Order), $"获取微信小程序的openid，调用接口地址：{serviceAddress}");

                string jscodeJson = RequestHelper.SendGet(serviceAddress);

                LogHelper.InfoLog(typeof(N_Order), $"获取微信小程序的openid，调用接口返回：{jscodeJson}");

                WxJscodeSessionResult wxJscodeSession = JsonHelper.JsonStrToObject<WxJscodeSessionResult>(jscodeJson);

                string errmsg;
                if (wxJscodeSession.errcode == 0)
                {
                    //返回用户信息
                    return new OperationResult<ChartUser>(true, "获取微信openid成功", new ChartUser
                    {
                        openid = wxJscodeSession.openid,
                        session_key = wxJscodeSession.session_key
                    });
                }
                else if (wxJscodeSession.errcode == -1)
                {
                    errmsg = "获取微信openid返回消息：系统繁忙，请稍候再试";
                }
                else if (wxJscodeSession.errcode == 40029)
                {
                    errmsg = "获取微信openid返回消息：code 无效";
                }
                else if (wxJscodeSession.errcode == 45011)
                {
                    errmsg = "获取微信openid返回消息：频率限制，每个用户每分钟100次";
                }
                else if (wxJscodeSession.errcode == 40163)
                {
                    errmsg = "获取微信openid返回消息：WxCode重复使用，一个WxCode只能使用一次";
                }
                else
                {
                    errmsg = $"获取微信openid返回：未知错误代码{wxJscodeSession.errcode}";
                }

                return new OperationResult<ChartUser>(false, errmsg);
            }
            catch (Exception ex)
            {
                LogHelper.ErrorLog("获取微信小程序openid出现异常", typeof(N_OrderBLL), ex);
                return new OperationResult<ChartUser>(false, "获取微信小程序openid出现异常：" + ex.Message);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="orderParams"></param>
        /// <param name="appId"></param>
        /// <returns></returns>
        /// <remarks>
        /// 修改记录：
        /// 2021-10-7：添加参数appId，如果不为空，那么去web.xml找“systemPayUrl_”+appId对应的付款接口地址，否则找systemPayUrl的接口地址
        /// </remarks>
        public OperationResult<WeChatUnifiedOrderModel> SystemPay(WeChatUnifiedOrderParams orderParams, string appId = null)
        {
            try
            {
                string payUrl = ConfigurationHelper.AppSetting("systemPayUrl");

                if (!string.IsNullOrEmpty(appId)) {
                    string k = $"systemPayUrl_{appId}";
                    payUrl = ConfigurationHelper.AppSetting(k);
                    if (string.IsNullOrEmpty(payUrl)) {
                        return new OperationResult<WeChatUnifiedOrderModel>(false, "调用付款系统,执行微信统一下单接口,根据传入的appId="+appId+"未获取到付款系统接口地址，请检查");
                    }
                }

                LogHelper.InfoLog(typeof(N_Order), $"调用付款系统，执行微信统一下单接口，付款系统接口地址：{payUrl}");

                string rbody = RequestHelper.SendPost(payUrl, orderParams);

                LogHelper.InfoLog(typeof(N_Order), $"调用付款系统，执行微信统一下单接口，付款系统接口返回：{rbody}");

                if (rbody.IndexOf("appId")!= -1)
                {
                    //没有表示正确下单，返回的预付单信息
                    SystemWxPayResult systemWxPayResult = JsonHelper.JsonStrToObject<SystemWxPayResult>(rbody);
                    return new OperationResult<WeChatUnifiedOrderModel>(true, "微信统一下单成功，返回预付单信息", systemWxPayResult.result);
                }
                else
                {
                    //下单失败
                    return new OperationResult<WeChatUnifiedOrderModel>(false, "微信统一下单失败：支付异常，请联系客服人员或稍后再试！");
                }
            }
            catch (Exception e) {
                LogHelper.ErrorLog("微信统一下单失败出现异常", typeof(N_OrderBLL), e);
                return new OperationResult<WeChatUnifiedOrderModel>(false, "微信统一下单失败出现异常");
            }
        }

        public OperationResult<WeChatUnifiedOrderModel> WebChartPreOrderPay(CreateOrder2Params orderParams)
        {
            var openIdResult = GetWebChartOpenId(orderParams.WxCode, orderParams.AppId);
            if (!openIdResult.Success) {
                //获取openId失败
                return new OperationResult<WeChatUnifiedOrderModel>(false,openIdResult.Message);
            }

            var orderResult = CreateOrder2(orderParams);
            if (!orderResult.Success) {
                //创建系统内部订单失败
                return new OperationResult<WeChatUnifiedOrderModel>(false, orderResult.Message);
            }

            var weChatUnifiedOrder = new WeChatUnifiedOrderParams(orderResult.Data.ParentOrderCode, orderResult.Data.CommodityMoney,openIdResult.Data.openid);
            weChatUnifiedOrder.key = "VR设备购买观看时长";
            weChatUnifiedOrder.Subject = "VR设备";
            var payResult = SystemPay(weChatUnifiedOrder, orderParams.AppId);
            if (!payResult.Success) {
                //调用微信统一下单接口失败
                return new OperationResult<WeChatUnifiedOrderModel>(false,payResult.Message);
            }

            return new OperationResult<WeChatUnifiedOrderModel>(true,"VR设备购买时间，下单成功，请使用此预付单信息发起支付",payResult.Data);
        }

        public OperationResult<WeChatUnifiedOrderModel> WebChartPreOrderPayDD(WebChartPreOrderPayDDParams ddParams)
        {
            var openIdResult = GetWebChartOpenId(ddParams.WxCode, ddParams.AppId);
            if (!openIdResult.Success)
            {
                //获取openId失败
                return new OperationResult<WeChatUnifiedOrderModel>(false, openIdResult.Message);
            }

            var orderResult = CreateOrder4(ddParams);
            if (!orderResult.Success)
            {
                //创建系统内部订单失败
                return new OperationResult<WeChatUnifiedOrderModel>(false, orderResult.Message);
            }

            //如果支付金额为空，那么执行微信支付的数据获取
            if (orderResult.Data.CommodityMoney == 0) 
            {
                return new OperationResult<WeChatUnifiedOrderModel>(false, "系统内部订单创建成功，计算后的实付金额为：0，不调用微信支付接口生成预付单信息");
            }


            var weChatUnifiedOrder = new WeChatUnifiedOrderParams(orderResult.Data.ParentOrderCode, orderResult.Data.CommodityMoney, openIdResult.Data.openid);
            weChatUnifiedOrder.key = "度度圈商品下单";
            weChatUnifiedOrder.Subject = "度度圈";
            if (orderResult.Data.CommodityNames.Length > 128)
            {
                weChatUnifiedOrder.Body = orderResult.Data.CommodityNames.Substring(0, 120)+"...";
            }
            else {
                weChatUnifiedOrder.Body = orderResult.Data.CommodityNames;
            }
            
            var payResult = SystemPay(weChatUnifiedOrder, ddParams.AppId);
            if (!payResult.Success)
            {
                //调用微信统一下单接口失败
                return new OperationResult<WeChatUnifiedOrderModel>(false, payResult.Message);
            }
            WeChatUnifiedOrderModel weChatUnifiedOrderModel = payResult.Data;
            weChatUnifiedOrder.ParentOrderCode = orderResult.Data.ParentOrderCode;
            return new OperationResult<WeChatUnifiedOrderModel>(true, "度度圈下单生成微信小程序预付单信息成功，请使用此预付单信息发起支付", weChatUnifiedOrderModel);
        }

        public OperationResult<WebChartPreOrderPayDDQRCodeResultModel> WebChartPreOrderPayDDQRCode(WebChartPreOrderPayDDQRCodeParams ddParams)
        {            
            var orderResult = CreateOrder4(ddParams.MapTo<WebChartPreOrderPayDDParams>());
            if (!orderResult.Success)
            {
                //创建系统内部订单失败
                return new OperationResult<WebChartPreOrderPayDDQRCodeResultModel>(false, orderResult.Message);
            }

            //如果支付金额为空
            if (orderResult.Data.CommodityMoney == 0)
            {
                return new OperationResult<WebChartPreOrderPayDDQRCodeResultModel>(false, "系统内部订单创建成功，计算后的实付金额为：0，不调用微信支付接口生成预付单信息");
            }

            //调用微信二维码支付接口，创建二维码 得到二维码显示地址            
            OperationResult<string> execWechatResult = ExecWechatQRCode(orderResult.Data.ParentOrderCode, orderResult.Data.CommodityMoney);
            if (!execWechatResult.Success) {
                return new OperationResult<WebChartPreOrderPayDDQRCodeResultModel>(false, "系统内部订单创建成功，调用微信支付接口失败："+execWechatResult.Message);
            }

            return new OperationResult<WebChartPreOrderPayDDQRCodeResultModel>(true, "操作成功，请用微信扫二维码进行支付。", new WebChartPreOrderPayDDQRCodeResultModel() { 
                QRCodeWebUrl = execWechatResult.Data,
                ParentOrderCode = orderResult.Data.ParentOrderCode
            });

        }

        /// <summary>
        /// 一个综合汇总接口，执行微信二维码扫码支付下单相关操作
        /// </summary>
        /// <param name="orderCode">系统内单号</param>
        /// <param name="commodityMoney">支付金额</param>
        /// <returns>成功返回二维码地址</returns>
        public OperationResult<string> ExecWechatQRCode(string orderCode, decimal commodityMoney) {
            //调用微信二维码支付接口
            WechatPayResult<AppPayOutput> wechatPayResult = SendWechatQRCode(orderCode, commodityMoney);
            if (!wechatPayResult.success)
            {
                return new OperationResult<string>(false, "调用微信支付接口返回失败：" + wechatPayResult.message);
            }

            //微信二维码支付接口返回成功
            AppPayOutput appPayOutput = wechatPayResult.data;
           
            //存储微信返回的内容
            N_WeiXinQRCode weiXinQRCode = appPayOutput.MapTo<N_WeiXinQRCode>();
            weiXinQRCode.OrderCode = orderCode;
            weiXinQRCode.Create_date = DateTime.Now;
            bLLSession.N_WeiXinQRCode.Add(weiXinQRCode);

            //创建二维码 得到二维码显示地址            
            string qrcodeUrl = CreateWechatQRCode(appPayOutput.CodeUrl, orderCode);
            return new OperationResult<string>(true, "度度圈扫码下单成功，请用微信扫此二维码完成支付", qrcodeUrl);
        }

        /// <summary>
        /// 发起微信二维码支付获取微信二维码
        /// </summary>
        /// <param name="orderCode">订单号</param>
        /// <param name="commodityMoney">支付金额</param>
        /// <returns></returns>
        public WechatPayResult<AppPayOutput> SendWechatQRCode(string orderCode, decimal commodityMoney) {
            if (commodityMoney <= 0) {
                return new WechatPayResult<AppPayOutput> { 
                    success = false,
                    message = "金额小于等于0"
                };
            }
            //构建二维码支付的参数
            AppPayInput input = new AppPayInput()
            {
                Body = "度度圈商品购买",
                OutTradeNo = orderCode,
                TotalFee = commodityMoney,
                SpbillCreateIp = RequestHelper.GetIP
            };

            WechatPayHelper wechatPayHelper = new WechatPayHelper();
            //调用微信接口
            WechatPayResult<AppPayOutput> wechatPayResult = wechatPayHelper.Pay(input);
            return wechatPayResult;
        }

        /// <summary>
        /// 创建微信支付 扫码的二维码
        /// </summary>
        /// <param name="wechatCodeUrl">微信接口返回的创建二维码的URL地址</param>
        /// <param name="orderCode">系统内部单号</param>
        /// <returns>返回在浏览器查看的二维码url地址</returns>
        public string CreateWechatQRCode(string wechatCodeUrl, string orderCode) {
            //文件上传路径
            HttpRequest request = RequestHelper.Request;
            //文件保存的物理路径
            string uploadPath = request.MapPath(request.ApplicationPath + DDQ_QRCODE_PATH);
            if (!Directory.Exists(uploadPath)) {
                Directory.CreateDirectory(uploadPath);
            }

            string saveFilePath;
            //二维码文件名称
            string fileName = QRCodeHelper.CreateQRCode(uploadPath, wechatCodeUrl, out saveFilePath, orderCode);

            //二维码Web查看地址            
            string qrcodeWebUrl = RequestHelper.GetApiRequestRootUrl() + DDQ_QRCODE_PATH + "/" + fileName;

            return qrcodeWebUrl;
        }

        /// <summary>
        ///  获取用户-购买商品有效期截止时间
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="fileId"></param>
        /// <returns></returns>
        public string GetPayEndTime(int userId, int fileId)
        {
            return DBSession.IN_OrderDAL.GetPayEndTime(userId, fileId);
        }

        public OperationResult ConfirmSendOutGoods(ConfirmSendOutGoodsParams param)
        {
            N_Order dbOrder = OrderDAL.FindSingle(w => w.OrderCode.Equals(param.OrderCode));
            if (dbOrder == null)
            {
                return new OperationResult(false, $"没有找到订单号：{param.OrderCode}的相关信息");
            }
            if (dbOrder.OrderState != OrderStateEnum.OrderState2)
            {
                return new OperationResult(false, $"只有订单状态为“买家已付款”才能确认发货，当前状态为“{OrderStateEnum.GetOrderStateName(dbOrder.OrderState)}”");
            }

            dbOrder.LogisticsOrderNo = param.LogisticsOrderNo;
            dbOrder.SendOutGoodsTime = DateTime.Now;
            dbOrder.SendOutGoodsUserId = param.SendOutGoodsUserId;
            dbOrder.OrderState = OrderStateEnum.OrderState7;

            T_User user = DBSession.IT_UserDAL.FindSingle(w => w.user_guid.Equals(param.userid));

            N_OrderLog orderLog = new N_OrderLog()
            {
                OrderCode = param.OrderCode,
                ParentOrderCode = dbOrder.ParentOrderCode,
                CreateTime = DateTime.Now,
                UserId = user.user_id,
                Content = $"用户：{user.user_name} 确认发货成功,订单编号：{param.OrderCode}"
            };
            
            using (TransactionScope transactionScope = new TransactionScope())
            {
                DBSession.IN_OrderLogDAL.Add(orderLog);
                DBSession.IN_OrderDAL.Modify(dbOrder, w => w.OrderCode.Equals(param.OrderCode), "LogisticsOrderNo", "SendOutGoodsTime", "SendOutGoodsUserId", "OrderState");

                transactionScope.Complete();
            }
            return new OperationResult(true, "订单确认发货成功");
        }

        public OperationResult ConfirmReceivingGoods(ConfirmReceivingGoodsParams param)
        {
            N_Order dbOrder = OrderDAL.FindSingle(w => w.OrderCode.Equals(param.OrderCode));
            if (dbOrder == null)
            {
                return new OperationResult(false, $"没有找到订单号：{param.OrderCode}的相关信息");
            }
            if (dbOrder.OrderState != OrderStateEnum.OrderState7)
            {
                return new OperationResult(false, $"只有订单状态为“卖家已发货”才能确认收货，当前状态为“{OrderStateEnum.GetOrderStateName(dbOrder.OrderState)}”");
            }

            dbOrder.OrderState = OrderStateEnum.OrderState4;
            //收货时间
            dbOrder.ReceivingGoodsTime = DateTime.Now;

            T_User user = DBSession.IT_UserDAL.FindSingle(w => w.user_guid.Equals(param.userid));

            N_OrderLog orderLog = new N_OrderLog()
            {
                OrderCode = param.OrderCode,
                ParentOrderCode = dbOrder.ParentOrderCode,
                CreateTime = DateTime.Now,
                UserId = user.user_id,
                Content = $"用户：{user.user_name} 确认收货成功,订单编号：{param.OrderCode}"
            };

            using (TransactionScope transactionScope = new TransactionScope())
            {
                DBSession.IN_OrderLogDAL.Add(orderLog);
                DBSession.IN_OrderDAL.Modify(dbOrder, w => w.OrderCode.Equals(param.OrderCode), "OrderState", "ReceivingGoodsTime");

                transactionScope.Complete();
            }
            //TODO：确认收货需要，计算销售额和积分，计算销售额和积分时，需要把订单中的商铺ID保存到销售明细和积分明细表
            return new OperationResult(true, "订单确认收货成功");
        }


        public OperationResult<OrderStatisticsModel> OrderStatistics(OrderStatisticsParams param)
        {
            T_User user = DBSession.IT_UserDAL.FindSingle(w => w.user_guid.Equals(param.userid));

            OrderStatisticsModel statisticsModel = OrderDAL.GetOrderStatistics(user.user_id, param);

            return new OperationResult<OrderStatisticsModel>(true, "获取订单统计数据成功", statisticsModel);
        }

        public OperationResult UpdateStorageStatus(UpdateStorageStatusParams param)
        {
            return OrderDAL.UpdateStorageStatus(param);

            //return new OperationResult(true, "更新订单备货状态成功，更新状态为：" + param.StorageStatus);
        }

        public OperationResult UpdateOrderReceivingUser(UpdateOrderReceivingUserParams param)
        {
            return OrderDAL.UpdateOrderReceivingUser(param);
        }

        public OperationResult GetParentGroupOrderTotal(GetParentGroupOrderTotalParams param)
        {
            return OrderDAL.GetParentGroupOrderTotal(param);
        }

        public OperationResult<GetStoreOrderStatModel> GetStoreOrderStat(GetStoreOrderStatParams param)
        {
            GetStoreOrderStatModel model = OrderDAL.GetStoreOrderStat(param);

            return new OperationResult<GetStoreOrderStatModel>(true, "查询成功", model);
        }

        public OperationResult<List<GetStoreGoodsStatModel>> GetStoreGoodsStat(GetStoreGoodsStatParams param)
        {
            var lists = OrderDAL.GetStoreGoodsStat(param);

            foreach (var order in lists)
            {
                if (!string.IsNullOrWhiteSpace(order.FileImage))
                {
                    order.FileImage = order.FileImage.Replace("~", HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.IndexOf("/api/")));
                }
            }

            return new OperationResult<List<GetStoreGoodsStatModel>>(true, "查询成功", lists);
        }

        public OperationResult GetOrderState(GetOrderStateParams param) {
            T_User user = DBSession.IT_UserDAL.FindSingle(w => w.user_guid.Equals(param.userid));

            var order = OrderDAL.FindSingle(w => w.ParentOrderCode.Equals(param.ParentOrderCode) && w.OrderCreateUserId == user.user_id);
            if (order == null) {
                return new OperationResult(false, "未找到订单");
            }

            return new OperationResult(true, "当前订单状态："+ OrderStateEnum.GetOrderStateName(order.OrderState), order.OrderState);
            
        }

        #region 私有方法

        /// <summary>
        /// 购买商品ID集合
        /// </summary>
        /// <param name="CommodityInfos"></param>
        /// <returns></returns>
        private List<int> ListCommodityId(List<PaymentAmountParamsCommodityInfo> CommodityInfos)
        {
            List<int> commodityIds = new List<int>(CommodityInfos.Count);

            foreach (PaymentAmountParamsCommodityInfo paymentAmountParamsCommodity in CommodityInfos)
            {
                commodityIds.Add(paymentAmountParamsCommodity.CommodityId.Value);
            }

            return commodityIds;
        }

        /// <summary>
        /// 检查 用户的金币和赠币是否足够支付订单的金额 并进行扣减
        /// </summary>
        /// <param name="paymentAmountModel">订单支付金额信息</param>
        /// <param name="user">购买用户</param>
        /// <param name="buyMoney">金币支付扣减数量</param>
        /// <param name="giveMoney">赠币支付扣减数量</param>
        /// <param name="giveBuyNum">需要金币支付的部分赠币额度</param>
        /// <returns>true 足够支付、false 不够支付</returns>
        private bool CheckUserMoney(PaymentAmountModel paymentAmountModel, ref T_User user, ref decimal buyMoney, ref decimal giveMoney, ref decimal giveBuyNum)
        {
            //不需要赠币支付
            if (paymentAmountModel.PreferentialAmount == 0)
            {
                //用户金币大于等于需要支付的金额
                if (user.buy_gold >= paymentAmountModel.CommodityMoney)
                {
                    buyMoney = paymentAmountModel.CommodityMoney;

                    user.buy_gold = user.buy_gold - paymentAmountModel.CommodityMoney;
                    return true;
                }
                else
                {
                    return false;
                }
            }

            //赠币足够支付赠币部分，金币足够支付金币部分
            if (user.give_gold >= paymentAmountModel.PreferentialAmount && user.buy_gold >= paymentAmountModel.PaymentAmount)
            {
                buyMoney = paymentAmountModel.PaymentAmount;
                giveMoney = paymentAmountModel.PreferentialAmount;

                user.buy_gold = user.buy_gold - paymentAmountModel.PaymentAmount;
                user.give_gold = user.give_gold - paymentAmountModel.PreferentialAmount;
                return true;
            }

            //赠币不够支付赠币部分，需要金币去支付金币+部分赠币不够的额度
            if (user.give_gold < paymentAmountModel.PreferentialAmount)
            {
                //需要金币支付的部分赠币额度
                giveBuyNum = paymentAmountModel.PreferentialAmount - user.give_gold;

                //需要金币支付的总额度
                buyMoney = paymentAmountModel.PaymentAmount - giveBuyNum;

                //金币足够支付
                if (user.buy_gold >= buyMoney)
                {
                    //赠币支付的额度
                    giveMoney = user.give_gold;

                    user.buy_gold = user.buy_gold - buyMoney;
                    user.give_gold = 0;
                    return true;
                }
            }

            return false;
        }

        /// <summary>
        /// 检查下单商品是否存在待付款订单
        /// </summary>
        /// <param name="submitOrderParams">下单参数</param>
        /// <param name="userId">下单用户ID</param>
        /// <returns></returns>
        private IList<string> CheckCommodityOrder(SubmitOrderParams submitOrderParams, int userId)
        {
            var result = new List<string>();

            submitOrderParams.CommodityInfos.ForEach((commodity) => {
                string orderCommodityName = DBSession.IN_OrderDAL.CheckCommodityUnpaidOrder(userId, commodity.CommodityId.Value);
                if (!string.IsNullOrEmpty(orderCommodityName))
                {
                    result.Add(orderCommodityName);
                }
            });

            return result;
        }

        /// <summary>
        /// 检查 商品是否在购物车中
        /// </summary>
        /// <param name="submitOrderParams">下单的商品信息</param>
        /// <param name="userId">下单用户ID</param>
        /// <returns></returns>
        private List<string> CheckShopping(SubmitOrderParams submitOrderParams, int userId)
        {
            var result = new List<string>();

            submitOrderParams.CommodityInfos.ForEach((commodity) => {
                var shopp = DBSession.IN_ShoppingDAL.FindSingle(w => w.FileId == commodity.CommodityId.Value && w.UserId == userId);
                if (shopp == null)
                {
                    //购物车不存在此商品
                    var fileInfo = DBSession.IT_DocumentInfoDAL.FindSingle(w => w.file_id == commodity.CommodityId.Value);
                    result.Add(fileInfo.file_name);
                }
            });

            return result;
        }

        /// <summary>
        /// 获取价格信息
        /// </summary>
        /// <param name="goodDisiPrices">购买商品的所有期限价格</param>
        /// <param name="commodify">商品ID和购买期限</param>
        /// <returns></returns>
        private T_VRGoodDisiPrice GetPriceInfo(List<T_VRGoodDisiPrice> goodDisiPrices, PaymentAmountParamsCommodityInfo commodify)
        {
            T_VRGoodDisiPrice commodifyGoodDisi = null;
            foreach (T_VRGoodDisiPrice goodDisiPrice in goodDisiPrices)
            {
                if (goodDisiPrice.op_month == commodify.PurchasePeriod.Value
                    && goodDisiPrice.file_id == commodify.CommodityId.Value)
                {
                    commodifyGoodDisi = goodDisiPrice;
                    break;
                }
            }

            return commodifyGoodDisi;
        }

        /// <summary>
        /// 获取商品价格信息
        /// </summary>
        /// <param name="opcode">价格代码</param>
        /// <returns></returns>
        private T_VRGoodDisiPrice GetPriceInfo(string opcode)
        {
            var p = DBSession.IT_VRGoodDisiPriceDAL.FindSingle(w => w.op_code.Equals(opcode));

            return p;
        }

        /// <summary>
        /// 检查设备是否运行中
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="commodityId">商品DI</param>
        /// <returns>true运行中、false未运行</returns>
        private bool CheckDeviceRun(int userId,int commodityId)
        {
            string fileName = DBSession.IN_OrderDAL.CheckCommodityPay(userId,commodityId);
            if (string.IsNullOrEmpty(fileName)) {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 检查设备是否已经购买并在24小时内
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="commodityId">商品ID</param>
        /// <returns>true24小时有效期内容、false超过24小时或已经使用</returns>
        private bool CheckDevice24TermOfValidity(int userId, int commodityId)
        {
            string fileName = DBSession.IN_OrderDAL.CheckDevice24TermOfValidity(userId, commodityId);
            if (string.IsNullOrEmpty(fileName))
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 总数据库配置表T_VRWebChartSet中获取AppId对应的密钥
        /// </summary>
        /// <param name="appId">APPID</param>
        /// <returns>返回null或密钥</returns>
        private string GetAppSecret(string appId) {
            if (string.IsNullOrEmpty(appId)) {
                return null;
            }
            T_VRWebChartSet webChartSet = VRWebChartSet.FindSingle(w => w.appid.Equals(appId));

            if (webChartSet == null) {
                return null;
            }
            return webChartSet.appsecret;
        }

        /// <summary>
        /// 检查 多个商品中是否有虚拟的商品
        /// </summary>
        /// <param name="CommodityInfos">提交的商品信息</param>
        /// <returns>trun有虚拟商品、 false没有虚拟商品</returns>
        private bool CheckFictitiousCommodity(List<T_DocumentInfo> commodityInfos) 
        {
            bool fictitious = false;
            foreach (T_DocumentInfo commodityInfo in commodityInfos) {
                if (!commodityInfo.isEntity) {
                    //有虚拟商品
                    fictitious = true;
                    break;
                }
            }

            return fictitious;
        }

       
        #endregion
    }
}
